<?php

namespace Common\Library\Job;

/**
 * 佣金处理类
 */
class Commission
{

    private $group_id,$model,$Obj,$Failed;

    public function __construct($group_id){
        $this->group_id = $group_id;
        $this->model = M('commission');
        $this->Obj = M('Order');
        $this->Failed = M('failed_commission');
    }

    public function handle(){
        $this->commissionHandle();
    }

    /**
     * 佣金处理
     */
    protected function commissionHandle(){
        //获取产生佣金的订单
        $orders = $this->getOrderList();
        //考虑无人参团，系统自动拼团的情况 对订单做非空判断
        if($orders){
            foreach ($orders as $key => $value) {
                $money = ($value['deal_money'] - $value['distribution_money']) * $value['num'];
                $data = [
                    'user_id' => $value['user_id'],
                    'group_id' => $this->group_id,
                    'order_id' => $value['id'],
                    'money' => $money,
                    'remark' => '订单id为:'.$value['id'].'的订单,订单金额为:'.$value['deal_money'] * $value['num'].'元,产生佣金:'.$money.'元'
                ];
                $id = $this->model->add($data);
                if(!$id){
                    $remark = '订单id为:'.$value['id'].'的订单产生佣金失败';
                    debug('订单id为:'.$value['id'].'的订单产生佣金失败');
                    debug($this->model->_sql());
                    $param = [
                        'order_id' => $value['id'],
                        'remark' => $remark,
                        'crdate' => time(),
                        'tstamp' => time()
                    ];
                    $this->Failed->add($param);
                }
            }
        }
    }

    private function getOrderList(){
        return $this->Obj->where(array('group_id' => $this->group_id,'is_collect_bills' => 0))->Field('id,num,deal_money,distribution_money,user_id')->select();
    } 
}
